package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.entity.AddressBook;
import com.sky.mapper.AddressBookMapper;
import com.sky.service.AddressBookService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class AddressBookServiceImpl implements AddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;



    @Override
    public AddressBook add(AddressBook addressBook) {
        //获取到当前用户id
        Long currentId = BaseContext.getCurrentId();
        addressBook.setUserId(currentId);
        //每次将新增地址设置为默认地址，将其他地址设置为非默认地址
        addressBook.setIsDefault(1);

        //将该用户的其他地址设定为非默认地址，通过userId查询到该用户的所有地址集合，然后遍历集合，将isDefault设置为0
        List<AddressBook> list = addressBookMapper.list(addressBook.getUserId());
        if(list != null && list.size() > 0){
            for (AddressBook book : list) {
              book.setIsDefault(0);
              addressBookMapper.update(book);
        }}
        addressBookMapper.insert(addressBook);


        return addressBook;
    }

    @Override
    public List<AddressBook> list() {
        //获取到当前用户id
        Long currentId = BaseContext.getCurrentId();
        List<AddressBook> list = addressBookMapper.list(currentId);
        return null;
    }

    @Override
    public AddressBook getDefault() {
        //获取到当前用户id
        Long currentId = BaseContext.getCurrentId();
        //查询当前用户的默认地址
        AddressBook addressBook = addressBookMapper.getDefault(currentId);
        return addressBook;
    }
}
